//
//  JPMgmtVC.swift
//  ANOA
//
//  Created by 邱仙凯 on 2022/4/8.
//  Copyright © 2025 aowang. All rights reserved.
//

import UIKit
let contractSUtil = KVArrayUtil(arr: [("","全部"),("0","未生成"),("1","已生成")])

class JPMgmtVC: ProductionBaseController,approvalFlowable {
    
 
    var dataArray = [JPMgmtModel]()
   

       var audit_mark = ""
    var z_record_no = ""
    var z_title = ""
     override func viewDidLoad() {
        super.viewDidLoad()
        self.page = 1
        self.title = "竞拍管理"
        
 
        let appe = KSFilterAppearance()
            .bgHeight(KSGlobal.screenH - 100)
         filterV = KSRaiseUpFilterV(startY:0,appearance: appe, arr: [SlideContent(type: .dateRegion,title: "日期", startDate:startDate,endDate:endDate),SlideContent(type: .singleInput,title: "单据编号", inputStr: z_record_no),SlideContent(type: .singleInput,title: "标题", inputStr: z_title),SlideContent(type: .singleSelect, title: "审核标识",dataArr: ["全部","未提交","已提交","已审核","已退回"].map{ SeString(title: $0, ks_selected: false) },numberOfRow: 3,open: true)])
 
        
        self.tableView.backgroundColor = Theme.awModuleBgColor
        self.tableView.separatorStyle = .none
        tableView.estimatedRowHeight = 100
        tableView.rowHeight = UITableView.automaticDimension
        tableView.register(GlobalTableViewCell.self, forCellReuseIdentifier: GlobalTableViewCell.identifier)
        tableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: 100, right: 0)
        
        
        tableView.mj_header = KSRefreshHeader { [unowned self] in
            self.page = 1
            self.network()
        }
        tableView.mj_footer = KSRefreshFooter { [unowned self] in
            self.page+=1
            self.network()
        }
        tableView.mj_header?.beginRefreshing()
        
         navigationItem.rightBarButtonItems = [addItem]

         configFilter()
     }
     func configFilter() {
          
        
         var t1 = inputTypeFilter(nm: "单据号", param: "z_record_no")

         var t2 = inputTypeFilter(nm: "标题", param: "z_title")
      
         var t3 = TemplateModel(JSON:["":""])!
         t3.isFormSHow = "1"
         t3.isFilterShow = "1"
         t3.field_nm = "audit_mark_nm"
         t3.field_annotation = "审核标识"
         t3.field_type = TemplateType.localSelect.rawValue
         t3.select_data = "0:未提交,1:已审核,2:已退回,9:已提交,-1:全部"
         t3.selectDataBack = LocalSelectDataBack(idBack: "audit_mark",nmBack: "audit_mark_nm")
         var t31 = TemplateModel(JSON:["":""])!
         t31.isFormSHow = "0"
         t31.isFilterShow = "0"
         t31.field_nm = "audit_mark"
         t31.field_type = TemplateType.input.rawValue


         
         let temf = [t_begin_dt,t_end_dt,t1,t2,t3,t31 ]

   
         let yyy = getTopH() + comSearchBanner.ks_height

         self.comSearchBanner.initWithFcontent(startY:yyy,templateFilter: temf)
         self.comSearchBanner.bannerComfirmClo = {
             if let isrefresh = self.tableView.mj_header?.isRefreshing,isrefresh {
                 self.tableView.mj_header?.endRefreshing()
                 DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
                     self.tableView.mj_header?.beginRefreshing()
                 }
             }  else {
                 self.tableView.mj_header?.beginRefreshing()
             }
         }
    
     }
  
    
    override func search() {
        self.filterV.confirmClosure = { arr in
            self.startDate = arr[0].startDate
            self.endDate = arr[0].endDate
            self.z_record_no = arr[1].inputStr
            self.z_title = arr[2].inputStr

            let ss = arr[3].dataArr!.filter{ $0.ks_selected }
            if ss.count > 0 {
                self.audit_mark = AuditStatusDesc[ss.first!.title]!
            } else {
                self.audit_mark = ""
            }
           
          
             self.filterV.close()
            self.tableView.mj_header?.beginRefreshing()
        }
        filterV.present()
        
        
    }
    override func network() {
        self.startDate = any2Str(comSearchBanner.filterV?.filterDic["begin_dt"])
        self.endDate = any2Str(comSearchBanner.filterV?.filterDic["end_dt"])
        self.audit_mark = any2Str(comSearchBanner.filterV?.filterDic["audit_mark"])
        self.z_record_no = any2Str(comSearchBanner.filterV?.filterDic["z_record_no"])
        self.z_title = any2Str(comSearchBanner.filterV?.filterDic["z_title"])
        let dic:[String:String] =  ["z_record_no":z_record_no,"z_title":z_title,"begin_dt":"\(self.startDate)","end_dt":"\(self.endDate)","page":"\(page)","size":"\(KSGlobal.pageSize)","z_audit_mark":self.audit_mark]
         KSNetwork.shared.doRequest(API.homepage(.JPMg_queryJpInfo(data: dictionaryToJson(dic))),showHud: false) {  [weak self] (data:BaseResultOK<JPMgmtModel>) in
            guard let `self` = self else {return}
            if data.flag == TRUE {
                if let infos = data.infos {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.dataArray += infos
                    self.tableView.reloadData()
                    self.tableView.mj_header?.endRefreshing()
                    self.tableView.mj_footer?.endRefreshing()
                    if infos.count < KSGlobal.pageSize {
                        self.tableView.mj_footer?.endRefreshingWithNoMoreData()
                    }
                    
                    
                }
            } else {
                KSToast(data.errorCombine.unwrap)
            }
        }
        
        
        
    }
    override func add() {
        
        
        let view  = JPMgmtForm.initForAdd()
        view.refreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
        }
        self.navigationController?.pushViewController(view, animated: true)
        
    }
    
    
 
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return self.dataArray.count
        
    }
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: GlobalTableViewCell.identifier, for: indexPath) as!
        GlobalTableViewCell
        
        let one = dataArray[indexPath.row]
        
        let titleAndStatus = ("\(one.zTitle.unwrap)",one.zAuditMarkName.unwrap)
        var contArr:[(String,String?)]!
        
        contArr = [
            ("竞拍编号","\(one.zRecordNo.unwrap)"),
            ("竞拍时间","\(one.zBeginDate.unwrap)至\(one.zEndDate.unwrap)"),
            ("数量","\(one.zNum.unwrap)"),
            ("均重(kg)","\(one.zAvgWeight.unwrap)"),
            ("起拍价(元)","\(one.zPrice.unwrap)"),
            ("竞拍状态","\(one.zStatusName.unwrap)"),
          ]
     
        var btnTitleArr:[String] = []
        
        if one.zAuditMark == "9" {
            btnTitleArr = ["反提交","流程图"]
        } else if one.zAuditMark == "1" {
            btnTitleArr = ["流程图"]
        } else {
            btnTitleArr = ["提交","修改","删除"]
        }
        
        
        cell.setDataSource(contentArr: contArr,btnTitleArr: btnTitleArr,titleAndStatus: titleAndStatus)
        
        
        cell.btnGroupclickAction = {[indexPath,one] tag,titlex in
             
            guard USERINFO.idKey.unwrap ==  self.dataArray[indexPath.row].zStaffId.unwrap else {
                KSToast("非制单人不能做此操作!")
                return
            }
            
 
            
            if titlex == "提交" {
                
                KSNetwork.shared.doRequest(API.homepage(.JPMg_referJpInfo(id_key: one.idKey.unwrap))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        KSToast("提交成功")
                        self.tableView.mj_header?.beginRefreshing()
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
                
            } else if titlex == "反提交" {
                
                KSNetwork.shared.doRequest(API.homepage(.JPMg_unreferJpInfo(id_key: one.idKey.unwrap))) { (data:BaseResult<OperateResult>) in
                    if data.flag == TRUE {
                        KSToast("反提交成功")
                        self.tableView.mj_header?.beginRefreshing()
                    } else {
                        KSToast(data.errorCombine.unwrap)
                    }
                }
                
            } else if titlex == "删除" {
                alertUtil(self, title: "确认删除？", operateS: [nameAction(name: "确定", action: { (_) in
                    
                    KSNetwork.shared.doRequest(API.homepage(.JPMg_delJpInfo(id_key: one.idKey.unwrap))) { (data:BaseResult<OperateResult>) in
                        if data.flag == TRUE {
                            KSToast("删除成功")
                            self.tableView.mj_header?.beginRefreshing()
                        } else {
                            KSToast(data.errorCombine.unwrap)
                        }
                     }
 
                })])
            }else if titlex == "修改" {
                let view  = JPMgmtForm.initForView(model: self.dataArray[indexPath.row])
                view.excuteType = .fix
                view.refreshClosure = {
                    self.tableView.mj_header?.beginRefreshing()
                }
                self.navigationController?.pushViewController(view, animated: true)
            }  else if titlex == "流程图" {
                // MARK: - 流程图
//                TempHelper.shared.viewFlowPic(controller: self, process: "", voc_cd: "JPXXZY", vou_id: one.idKey.unwrap)
                
                
                if one.newFlow == "0" {
                    TempHelper.shared.viewFlowPic(controller: self, process: "", voc_cd: "JPXXZY", vou_id: one.idKey.unwrap)

                } else {
                    let oneXX  =  ["查看流程", "voc_cd=${a.voc_cd}&vou_id=${a.id_key}", "0", "flow"]
                    let dicxx  =  ["id_key": "\(one.idKey.unwrap)", "voc_cd": "JPXXZY"]

                    go2Flow(oneXX: oneXX, chooseUser: [], one: dicxx, vc: self)
                }
            }
            
        }
        
        
        
        
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let view  = JPMgmtForm.initForView(model: self.dataArray[indexPath.row])
        view.refreshClosure = {
            self.tableView.mj_header?.beginRefreshing()
        }
        self.navigationController?.pushViewController(view, animated: true)
        
    }
}
